﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using nhCore.Modbus;

namespace nhCore
{
    /// <summary>
    /// 设备命令及解析的辅助类，临时保存命令及解析，联系窗体和服务
    /// </summary>
    public class CmdAnalysisHelp
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 设备地址
        /// </summary>
        public byte Address { get; set; }

        /// <summary>
        /// 设备云ID
        /// </summary>
        public byte Id { get; set; }

        /// <summary>
        /// 使用的最大寄存器，用于生产命令，默认值为null
        /// </summary>
        private ushort MaxReg { get; set; }

        private ushort MinReg { get; set; }

        private byte ControlCode { get; set; }

        private bool IsCgq { get; set; }



        /// <summary>
        /// 构造函数，新建一个记录仪，CmdHelpers字典加入实时、历史、校时命令
        /// </summary>
        /// <param name="address"></param>
        /// <param name="maxReg"></param>
        /// <param name="minReg"></param>
        /// <param name="controlCode">为0时为记录仪</param>
        public CmdAnalysisHelp(byte address, UInt16 maxReg, ushort minReg, byte controlCode, byte id = 0)
        {
            Name = "命令及解析的辅助类";
            Address = address;
            Id = id;

            MaxReg = maxReg;
            MinReg = minReg;
            IsCgq = controlCode != 0;
            ControlCode = controlCode == 0 ? (byte)0x04 : controlCode;
            Id = id;
        }

        /// <summary>
        /// 取命令列表，新建命令列表，新建命令，气象命令附加解码器，时间和配置命令无解码器
        /// </summary>
        /// <returns></returns>
        public List<CmdFrame> GetSentCmds()
        {
            List<CmdFrame> ls = new List<CmdFrame>();

            //实时命令
            RealTimeCmd rtc = new RealTimeCmd(Address, ControlCode)
            {
                Index = MinReg,
                Len = (byte)(MaxReg - MinReg + 1)
            };
            (rtc.Analyzer as WeatherAnalyzer).Decoders = Decoders;
            ls.Add(rtc);

            if (!IsCgq)
            {
                //历史命令
                HistoryCmd hc = new HistoryCmd(Address);
                (hc.Analyzer as WeatherAnalyzer).Decoders = Decoders;
                ls.Add(hc);
                //校时命令
                CalibrationTimeCmd dtc = new CalibrationTimeCmd(Address);
                ls.Add(dtc);
            }
            return ls;
        }

        /// <summary>
        /// 气象数据解码器列表
        /// </summary>
        public List<Modbus.Decoder> Decoders { get; set; } = new List<Modbus.Decoder>();

    }
}
